<template>
  <el-form-item
    :label="label"
    :label-width="labelWidth"
    :prop="props.data.field"
    :required="props.data.required"
    :rules="props.data.rules"
  >
    <el-checkbox-group
      v-model="val"
      :style="style"
      :size="props.data.style == 'button' ? props.data.size : 'default'"
      :readonly="props.data.readonly"
      :disabled="props.data.disabled || props.data.readonly"
      @change="onChange"
    >
      <component
        :is="props.data.style == 'default' ? ElCheckbox : ElCheckboxButton"
        v-for="item in options"
        :label="item"
        :key="item"
        >{{ item }}</component
      >
    </el-checkbox-group>
  </el-form-item>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElFormItem, ElCheckboxGroup, ElCheckbox, ElCheckboxButton } from 'element-plus'
import { useProps } from '../../common-props/hooks'

const props = defineProps<{ data: Record<string, any>; form: Record<string, any> }>()
const emits = defineEmits(['valueChange'])

const { label, labelWidth } = useProps(props)
const val = ref()

const style = computed(() => {
  const css: any = { width: `${props.data.compWidth || 100}%` }
  if (props.data.align == 'vertical') {
    css['display'] = 'grid'
    if (props.data.style == 'button') {
      css['gap'] = '4px'
    }
  }
  return css
})
const options = computed(() => {
  const opts = props.data.options
  if (opts) {
    return opts.split('\n')
  } else {
    return []
  }
})

watch(
  () => props.data.defaultVal,
  () => {
    if (props.data.defaultVal) {
      val.value = props.data.defaultVal.split(',')
      emits('valueChange', { name: props.data.field, value: props.data.defaultVal })
    }
  },
  { immediate: true }
)

const onChange = (_val: any[]) => {
  const data = props.data
  data.defaultVal = _val.join(',')
  emits('valueChange', { name: props.data.field, value: data.defaultVal })
}
</script>

<style lang="scss" scoped></style>
